<?php
namespace  App\Http\Controllers\Radius;
use  App\Http\Controllers\Controller;

use App\Order;
use App\Rad_user;
use App\Rad_user_account;
use Illuminate\Http\Request;

use App\Common\ErrorDefine;

use App\Radacct;
use App\Radcheck;
use App\Radgroupcheck;
use App\Radreply;
use App\Radusergroup;
use App\Rad_manage;
use App\Radgroupreply;
use App\Rad_users;
use App\Rad_account;
use App\Rad_merge_data;
use DB;
use App\Rad_manage_discount;
use App\Rad_order;
use App\Line;
use App\Agent;
use App\Teamqq;

use App\Manage_user_list;
use App\Discount;

use Redis;
use App\Terrace;
use App\Http\Controllers\Radius\ModuleController;

class UserController extends Controller
{


    private static $_ch;
    var $redis_;
    var $module;

    function __construct()
    {
        $this->module = new ModuleController();
        $this->redis_ = null;

    }


    function __destruct()
    {
        if($this->redis_ != null) {
            $this->redis_->close();
        }
    }


    static function connectRedis()
    {
        $redis_ = new Redis();
        $redis_->connect("127.0.0.1", "6379");
        return $redis_;
    }


    /**
     *
     * 数据更新 每天删除用户金额
     */

    public function updateData()
    {
        $users = Rad_users::all()->toArray();

        foreach($users as $value)
        {
            $radreply = Radreply::where('username',$value['username'])->get()->toArray();
            if(empty($radreply))
            {
                $param['username'] = $value['username'];
                $param['attribute'] = 'Mikrotik-Rate-Limit';
                $param['op'] = '=';
                $param['value'] = '2048k/2048k';

                $id = Radreply::insertGetId($param);

                if($id)
                {
                    echo '------------------'.$value['username'].'-----------上下行'.$param['value'].'--------插入成功';
                }
            }
        }

    }






    //可以指定前缀   生成用户ID
    static function createUuid($prefix = "")
    {
        $str = md5(uniqid(mt_rand(), true));
        $uuid  = substr($str,0,8) . '-';
        $uuid .= substr($str,8,4) . '-';
        $uuid .= substr($str,12,4) . '-';
        $uuid .= substr($str,16,4) . '-';
        $uuid .= substr($str,20,12);
        return $prefix . $uuid;
    }


    /**
     * @param Request $request
     * parm username  用户名
     * param password  密码
     * return array()
     */
    public function createUser(Request $request)
    {
        $where = [];
        if(empty($request->all()))
        {
            self::ShowError(ErrorDefine::EMPTY_POST_DATA);
            return;
        }

        //  名称
        if(!$request->has('username') && !empty($request->input('username')))
        {
            self::ShowError(ErrorDefine::NAME_NOT_EXIST);
            return;
        }
        $where['username'] = $request->input('username');

        //  密码
        if(!$request->has('password') &&  !empty($request->input('password')))
        {
            self::ShowError(ErrorDefine::SHORT_OF_PASSWORD);
            return;
        }
        $where['password'] = $request->input('password');

        $user = Rad_user::where($where)->get()->toArray();

        if(!empty($user))
        {
            self::ShowError(ErrorDefine::USER_IS_EXIST);
            return;
        }
        $ret = Rad_user::insert($where);
        $user = Rad_user::where($where)->first();
        $token = md5($user->user_id.'niumokeji'.time());
        $user->token = $token;
        $user->save();

        return self::ShowMessage();


    }


    /**
     * 登录
     * param name(用户名)
     * param  password
     * return array() 用户信息
     */
    public function login(Request $request)
    {
        if(empty($request->all()))
        {
            self::ShowError(ErrorDefine::EMPTY_POST_DATA);
            return;
        }

        $where = [];
        //  名称
        if(!$request->has('username') && !empty($request->input('username')) )
        {
            self::ShowError(ErrorDefine::NAME_NOT_EXIST);
            return;
        }
        $where['username'] = $request->input('username');

        //  密码
        if(!$request->has('password') && !empty($request->input('password')))
        {
            self::ShowError(ErrorDefine::SHORT_OF_PASSWORD);
            return;
        }
        $where['password'] = $request->input('password');


        $user = Rad_manage::where($where)->get(['manage_id','username','balance','level'])->toArray();


        if(empty($user))
        {
            self::ShowError(ErrorDefine::ACCOUNT_OR_PASSOERD_DIE);
            return;
        }
        $time = date('Y-m-d H:i:s',time()-86400);       //  过期一天

        $info = Rad_manage::find($user[0]['manage_id']);
        $token = md5($user[0]['manage_id'].'niumokeji'.time());
        $info->token = $token;
        $info->save();

        $qq ='';
        $res = Teamqq::where('manage_id',$user[0]['manage_id'])->first();
        if($res)
        {
            $qq = $res->qq;
        }

        $data = array(
            'qq'=>$qq,
            'token'=>$token,
            'info'=>$user[0]
        );

        return self::ShowMessage($data);


    }

    /**
     * 退出
     * param user_id
     * return array()
     */

    public function logout(Request $request)
    {

        if(!$request->has('token') && !empty($request->input('token')))
        {
            self::ShowError(ErrorDefine::TOKEN_NOT_EXIST);
            return;
        }
        $token = $request->input('token');

        $user = Rad_manage::where('token',$token)->first();
        $user->token = '';
        $user->save();

        return self::ShowMessage();

    }

    /**
     * @param Request $request
     * 用户详情
     */
    public function getUserInfo(Request $request)
    {
        if(!$request->has('token') && empty($request->input('token')))
        {
            self::ShowError(ErrorDefine::TOKEN_NOT_EXIST);
            return;
        }
        $token = $request->input('token');

        //   获取用户ID
        $users = self::getTokenById($token);


        if(empty($users))
        {
            return self::ShowError(ErrorDefine::TOKEN_IS_EXPIRERD);
        }
        $user_id =  $users[0]['manage_id'];


//        $discount = Rad_manage_discount::where('manage_id',$user_id)->get()->toArray();
//        if(!empty($discount))
//        {
//            $discount = $discount[0];
//        }

        $info = Rad_manage::find($user_id);


        $province = Line::where('enable_flag','1')->distinct()->get(['province'])->toArray();

        foreach($province as $key=>&$value)
        {
            $line = Line::where('enable_flag','1')->where('province',$value['province'])->get(['province','city','carrieroperator','ip'])->toArray();
            $value['city'] = $line;
        }

        $data['line'] = $province;
        $data['info'] = $info;
//        $data['discount'] = $discount;

        return self::ShowMessage($data);

    }


    /**
     * @param Request $request
     * @return bool|void
     * 检测用户名
     */

    public function checkUserName(Request $request)
    {
        if(!$request->has('username') && empty($request->input('username')))
        {
            self::ShowError(ErrorDefine::NAME_NOT_EXIST);
            return;
        }
        $username = $request->input('username');
        $ret = Radcheck::where('username',$username)->get()->toArray();

        $data = [];
        if(!empty($ret))
        {
            $data['tag'] ='error';
        }else{
            $data['tag']='success';
        }

        return self::ShowMessage($data);
    }




    /**
     * @param Request $request
     * 管理员优惠列表
     */
    public function getManageInfo(Request $request)
    {

        if(!$request->has('token') && empty($request->input('token')))
        {
            self::ShowError(ErrorDefine::TOKEN_NOT_EXIST);
            return;
        }
        $token = $request->input('token');

        //   获取用户ID
        $user = self::getTokenById($token);


        $manage_id=  $user[0]['manage_id'];

        $manage_list = [];

        if($user[0]['level'] == 2)
        {
            $manage_list =  Rad_manage::get(['manage_id', 'username']);
        }


        $discount = Rad_manage::where('manage_id',$manage_id)->get(['primary-day','primary-week','primary-month','middle-day','middle-week','middle-month','height-day','height-week','height-month']);
        if(!empty($discount)){
            $discount = $discount[0];
        }

        $data = array(
            'discount'=>$discount,
            'list'=>$manage_list,
        );

        return self::ShowMessage($data);
    }





    /**
     * @param Request $request
     * 获取账号列表
     */
    public function getAccountList(Request $request)
    {

        $page_no = 0;
        $page_size =20;
        $username = '';
        $end_date = date('Y-m-d H:i:s',time());
        $start_date = '1970-01-01 08:00:00';
        $count = 0;
        $user_id = '';

        $result = [];


        $sql ="select user_id as id,username,password,con_max as connect_num,created_at,account_type,expired_at,manage_id,set_meal_type,terrace_id,remark from users ";
        $sql_count = "select count(user_id) as num  from users";

        if($request->input('page_no'))
        {
            $page_no  = $request->input('page_no');
            if($page_no){
                $page_no = $page_no - 1;
                if(is_numeric($page_no)){
                    if($page_no<0){
                        $page_no = 0;
                    }
                }
            }
        }

        if($request->input('page_size'))
        {
            $page_size = $request->input('page_size');
            if($page_size){
                if($page_size <=0 ){
                    $page_size =  20;
                }
            }
        }


        // 查询时间
        if($request->has('end_date') && !empty($request->input('end_date')))
        {
            $end_date = $request->input('end_date');
        }

        $sql .=" where  created_at < '{$end_date}'";
        $sql_count .=" where  created_at < '{$end_date}'";

        if($request->has('start_date') && !empty($request->input('start_date')))
        {
            $start_date = $request->input('start_date');
        }

        $sql .=" and  created_at > '{$start_date}'";
        $sql_count .=" and  created_at > '{$start_date}'";


        if($request->has('username') && !empty($request->input('username')))
        {
            $username = $request->input('username');
            $sql .=" and  username like '%{$username}%'";
            $sql_count .=" and  username like '%{$username}%'";
        }


        if(!$request->has('token') && empty($request->input('token')))
        {
            self::ShowError(ErrorDefine::TOKEN_NOT_EXIST);
            return;
        }
        $token = $request->input('token');

        //   获取用户ID
        $user = self::getTokenById($token);


        if(empty($user))
        {
            return self::ShowError(ErrorDefine::TOKEN_IS_EXPIRERD);
        }


        if($request->has('manage_name') && !empty($request->input('manage_name')))
        {
            $manage_name = $request->input('manage_name');

            $res = Rad_manage::where('username',$manage_name)->first();

            if($res)
            {
                $user_id = $res->manage_id;

                $sql .=" and manage_id ='{$user_id}' ";
                $sql_count .=" and  manage_id ='{$user_id}' ";
            }
        }

        if($request->has('account_type') && !empty($request->input('account_type')) && $request->input('account_type')!="undefined")
        {
            $account_type = $request->input('account_type');
            $sql .=" and  account_type ='{$account_type}' ";
            $sql_count .=" and  account_type ='{$account_type}' ";
        }


        $manage_id=  $user[0]['manage_id'];

        if($user[0]['level'] !=2)
        {
            $sql .=" and manage_id ='{$manage_id}' ";
            $sql_count .=" and  manage_id ='{$manage_id}' ";
        }



        if($request->has('expired_at') && !empty($request->input('expired_at')))
        {

            $expired_at = $request->input('expired_at');

            $expired_start= date('Y-m-d H:i:s',time());

            switch($expired_at)
            {
                case "未到期":$sql .= " and expired_at > '{$expired_start}' ";
                    $sql_count .= " and expired_at > '{$expired_start}' "; break;

                case "已到期":$sql .= " and expired_at < '{$expired_start}' ";
                    $sql_count .= " and expired_at < '{$expired_start}' ";break;

                case "近三天到期":
                    $expired_end = date('Y-m-d H:i:s',time()+86400*3);
                    $sql .= " and expired_at < '{$expired_end}' and expired_at >'{$expired_start}' ";
                    $sql_count .= " and expired_at < '{$expired_end}' and expired_at >'{$expired_start}' ";break;

                case "近七天到期":
                    $expired_end = date('Y-m-d H:i:s',time()+86400*7);
                    $sql .= " and expired_at < '{$expired_end}' and expired_at >'{$expired_start}' ";
                    $sql_count .= " and expired_at < '{$expired_end}' and expired_at >'{$expired_start}' ";break;
                default:break;
            }

        }


        if($request->has('set_meal_type') && !empty($request->input('set_meal_type')))
        {
            $type = $request->input('set_meal_type');

            switch($type)
            {
                case 1: $sql .= " and set_meal_type = 1 ";$sql_count .= " and set_meal_type = 1 ";break;
                case 2: $sql .= " and set_meal_type = 2 ";$sql_count .= " and set_meal_type = 2 ";break;
                case 3: $sql .= " and set_meal_type = 3 ";$sql_count .= " and set_meal_type = 3 ";break;
                default:break;
            }

        }


        if($request->has('type') && !empty($request->input('type')))
        {
            if($request->has('sort_name') && !empty($request->input('sort_name')))
            {
                $sort_name= $request->input('sort_name');
                $sort_value= $request->input('sort_value');

                $sql .= "   order by $sort_name $sort_value ";
            }

        }else{
            $sql .= " order by created_at desc ";
        }



        $discount = Rad_manage::where('manage_id',$manage_id)->get(['primary-day','primary-week','primary-month','middle-day','middle-week','middle-month','height-day','height-week','height-month']);


        if(!empty($discount))
        {
            $discount = $discount[0];
        }else{
            $discount = [];
        }

        $level = $user[0]['level'];
        $time = date('Y-m-d H:i:s',time());


        $user = new Rad_users();



        $no = $page_no*$page_size;
        $sql .= " limit $no,$page_size ";

        $arr = self::getSuperAdminData($sql,$sql_count);


        $users = $arr['users'];
        $count = $arr['count'];


        $page_total = ceil($count /$page_size);


        //   筛选类型

        $terrace = Terrace::all()->toArray();
        $manage = Rad_manage::all()->toArray();

        $terrace_arr = [];
        $manage_arr = [];

        foreach($terrace as $item)
        {
            $terrace_arr["{$item['id']}"] = $item['terrace_name'];
        }

        foreach($manage as $res)
        {

            $manage_arr["{$res['manage_id']}"] = $res['username'];
        }

        foreach($users as $key=>&$value)
        {

            if(array_key_exists($value['manage_id'], $manage_arr)){
                $value['manage_name'] = $manage_arr["{$value['manage_id']}"];
            }



            if(array_key_exists($value['terrace_id'], $terrace_arr)){
                $value['manage_name'] = $terrace_arr["{$value['terrace_id']}"];
            }


            if(strtotime($value['expired_at']) - time() >= 0)
            {

                if(strtotime($value['expired_at']) - time() < 86400*2)
                {
                    $value['time'] ='即将到期';
                    $value['expired'] =1;
                }else{
                    $value['time'] ='';
                    $value['expired'] =0;           //  到期标识   0  未到期
                }

            }else{

                $value['time'] ='已到期';
                $value['expired'] =2;           //  1 已到期
            }



            switch($value['set_meal_type'])
            {
                case 1:$value['set_meal'] = '基础套餐';break;
                case 2:$value['set_meal'] = '中等套餐';break;
                case 3:$value['set_meal'] = '高级套餐';break;
            }


            $res = Radreply::where('username',$value['username'])->first();
            $value['value'] = '';
            if($res)
            {
                $value['value'] = $res->value;
            }
        }

        $data = array(
            'count'=>$count,
            'page_total'=>$page_total,
            'level'=>$level,
            'discount'=>$discount,
            'account'=>$users
        );


        return self::ShowMessage($data);

    }

    /**
     * @param $start_date
     * @param $end_date
     * @param $username
     * @param $orderbytype
     * @param $orderBy
     * @param $page_no
     * @param $page_size
     * @return array
     * 超级管理员获取数据
     */
    static function getSuperAdminData($sql,$sql_count)
    {


        $users = DB::connection('mysql_concent')->select("$sql");

        $count = DB::connection('mysql_concent')->select("$sql_count");

        $res = [];
        foreach($users as $key=>$value)
        {
            $res[$key]['id'] = $value->id;
            $res[$key]['username'] = $value->username;
            $res[$key]['password'] = $value->password;
            $res[$key]['connect_num'] = $value->connect_num;
            $res[$key]['created_at'] = $value->created_at;
            $res[$key]['account_type'] = $value->account_type;
            $res[$key]['expired_at'] = $value->expired_at;
            $res[$key]['manage_id'] = $value->manage_id;
            $res[$key]['set_meal_type'] = $value->set_meal_type;
            $res[$key]['terrace_id'] = $value->terrace_id;
            $res[$key]['remark'] = $value->remark;
        }
        $arr = array(
            'users'=>$res,
            'count'=>$count[0]->num
        );

        return $arr;

    }




//    /**
//     * @param Request $request
//     * 获取账号列表
//     */
//    public function getAccountList(Request $request)
//    {
//
//        $page_no = 0;
//        $page_size =50;
//        $username = '';
//        $end_date = date('Y-m-d H:i:s',time());
//        $start_date = '1970-01-01 08:00:00';
//        $count = 0;
//        $user_id = '';
//
//        $result = [];
//
//        if($request->input('page_no'))
//        {
//            $page_no  = $request->input('page_no');
//            if($page_no){
//                $page_no = $page_no - 1;
//                if(is_numeric($page_no)){
//                    if($page_no<0){
//                        $page_no = 0;
//                    }
//                }
//            }
//        }
//
//        if($request->input('page_size'))
//        {
//            $page_size = $request->input('page_size');
//            if($page_size){
//                if($page_size <=0 ){
//                    $page_size =  50;
//                }
//            }
//        }
//
//        if($request->has('username') && !empty($request->input('username')))
//        {
//            $username = $request->input('username');
//        }
//
//
//        if(!$request->has('token') && empty($request->input('token')))
//        {
//            self::ShowError(ErrorDefine::TOKEN_NOT_EXIST);
//            return;
//        }
//        $token = $request->input('token');
//
//        //   获取用户ID
//        $user = self::getTokenById($token);
//
//
//        // 查询时间
//        if($request->has('end_date') && !empty($request->input('end_date')))
//        {
//            $end_date = $request->input('end_date');
//        }
//
//        if($request->has('start_date') && !empty($request->input('start_date')))
//        {
//            $start_date = $request->input('start_date');
//        }
//
//        if(empty($user))
//        {
//            return self::ShowError(ErrorDefine::TOKEN_IS_EXPIRERD);
//        }
//
//        $manage_id=  $user[0]['manage_id'];
//        $discount = Rad_manage::where('manage_id',$manage_id)->get(['primary-day','primary-week','primary-month','middle-day','middle-week','middle-month','height-day','height-week','height-month']);
//
//        if($discount)
//        {
//            $discount = $discount[0];
//        }else{
//            $discount = [];
//        }
//
//        $level = $user[0]['level'];
//
//
//        $time = date('Y-m-d H:i:s',time());
//
//
//        $user = new Rad_users();
//
//        if($request->has('manage_name') && !empty($request->input('manage_name')))
//        {
//            $manage_name = $request->input('manage_name');
//
//            $res = Rad_manage::where('username',$manage_name)->first();
//
//            if($res)
//            {
//                $user_id = $res->manage_id;
//            }
//        }
//
//
//        if($user_id)
//        {
//            $arr = self::getSystemManagerData($user_id,$start_date,$end_date,$username,$page_no,$page_size);
//        }else if($level != 2)
//        {
//            $arr = self::getSystemManagerData($manage_id,$start_date,$end_date,$username,$page_no,$page_size);
//        }else{
//            $arr = self::getSuperAdminData($start_date,$end_date,$username,$page_no,$page_size);
//        }
//
//        $users = $arr['users'];
//        $count = $arr['count'];
//
//        //   筛选类型
//
//
//        $radcheck = new Radcheck();
//
//
//        $result =$user->leftJoin("radreply", function ($join) {
//            $join->on("radreply.username", "=", "users.username");
//        })->leftJoin("terrace", function ($join) {
//            $join->on("users.terrace_id", "=", "terrace.id");
//        })->leftJoin("manage", function ($join) {
//            $join->on("manage.manage_id", "=", "users.manage_id");
//        })->whereIn('users.user_id',$users)->orderBy('created_at','desc')
//            ->get(array(
//                'users.user_id as id',
//                'users.username',
//                'users.password',
//                'users.con_max as connect_num',
//                'users.created_at',
//                'users.account_type',
//                'users.expired_at',
//                'users.remark',
//                'users.manage_id',
//                'terrace.terrace_name',
//                'manage.username as manage_name',
//                'radreply.value',
//                'users.set_meal_type',
//            ))->toArray();
//
//        foreach($result as $key=>&$value)
//        {
//
//            if(strtotime($value['expired_at']) - time() >= 0)
//            {
//
//                if(strtotime($value['expired_at']) - time() < 86400*2)
//                {
//                    $value['time'] ='即将到期';
//                }else{
//                    $value['time'] ='';
//                }
//
//            }else{
//
//                $value['time'] ='已到期';
//            }
//
//
//            switch($value['set_meal_type'])
//            {
//                case 1:$value['set_meal'] = '基础套餐';break;
//                case 2:$value['set_meal'] = '中等套餐';break;
//                case 3:$value['set_meal'] = '高级套餐';break;
//            }
//
//        }
//
//
//        $data = array(
//            'count'=>$count,
//            'discount'=>$discount,
//            'account'=>$result
//        );
//
//
//        return self::ShowMessage($data);
//
//    }
//
//    /**
//     * @param $start_date
//     * @param $end_date
//     * @param $username
//     * @param $orderbytype
//     * @param $orderBy
//     * @param $page_no
//     * @param $page_size
//     * @return array
//     * 超级管理员获取数据
//     */
//    static function getSuperAdminData($start_date,$end_date,$username,$page_no,$page_size)
//    {
//        $users = Rad_user::where('created_at','>',"{$start_date}")->where('created_at','<',"{$end_date}")->where('username','like','%'.$username.'%')
//            ->orderBy('created_at','desc')->offset($page_no*$page_size)->limit($page_size)->get(['user_id']);
//
//        $count = Rad_user::where('created_at','>',"{$start_date}")->where('created_at','<',"{$end_date}")->where('username','like','%'.$username.'%')->count();
//
//        $arr = array(
//            'users'=>$users,
//            'count'=>$count
//        );
//
//        return $arr;
//
//    }
//
//    /**
//     * @param $manage_id
//     * @param $start_date
//     * @param $end_date
//     * @param $username
//     * @param $orderbytype
//     * @param $orderBy
//     * @param $page_no
//     * @param $page_size
//     * @return array
//     * 普通管理员获取数据
//     */
//
//    static function getSystemManagerData($manage_id,$start_date,$end_date,$username,$page_no,$page_size)
//    {
//        $users = Rad_user::where('manage_id',$manage_id)->where('created_at','>',"{$start_date}")->where('created_at','<',"{$end_date}")->where('username','like','%'.$username.'%')
//            ->orderBy('created_at','desc')->offset($page_no*$page_size)->limit($page_size)->get(['user_id']);
//
//        $count = Rad_user::where('manage_id',$manage_id)->where('created_at','>',"{$start_date}")->where('created_at','<',"{$end_date}")->where('username','like','%'.$username.'%')->count();
//
//        $arr = array(
//            'users'=>$users,
//            'count'=>$count
//        );
//
//        return $arr;
//    }
//
//





    /**
     * 添加账号
     *param name 用户名
     *param password 密码
     *param date  天数
     *param type  类型
     *param concent_num 连接数
     *
     * return array();
     */
    public function addAcouunt(Request $request)
    {
        if(empty($request->all()))
        {
            self::ShowError(ErrorDefine::EMPTY_POST_DATA);
            return;
        }

        //  名称
        if(!$request->has('username') && empty($request->input('username')) )
        {
            self::ShowError(ErrorDefine::NAME_NOT_EXIST);
            return;
        }

        $username = trim($request->input('username'));


        //  密码
        if(!$request->has('password') && empty($request->input('password')))
        {
            self::ShowError(ErrorDefine::SHORT_OF_PASSWORD);
            return;
        }

        $password =  trim($request->input('password'));


        //  账号类型
        if(!$request->has('account_type') && empty($request->input('account_type')))
        {
            self::ShowError(ErrorDefine::ACCOUNT_TYPE_ONT_EXIST);
            return;
        }
        $account_type = $request->input('account_type');


        //  连接数
        if(!$request->has('concent_num') && empty($request->input('concent_num')) )
        {
            self::ShowError(ErrorDefine::CONCENT_NOT_EXIST);
            return;
        }
        $concent_num = $request->input('concent_num');

        //   检测连接数
        if($concent_num <=0 )
        {
            self::ShowError(ErrorDefine::ILLEGAL_CONNECT_NUM);
            return;
        }



        //   用户token
        if(!$request->has('token') && !empty($request->input('token')))
        {
            self::ShowError(ErrorDefine::TOKEN_NOT_EXIST);
            return;
        }
        $token = $request->input('token');

        //    备注
        $remark = '';
        if($request->input('remark'))
        {
            $remark = trim($request->input('remark'));
        }

        //    agent.niumoip.com 平台标识
        $agent = 0;
        if($request->input('agent'))
        {
            $agent = $request->input('agent');
        }

        //    manage.niumoip.com 平台标识
        $manage = 0;
        if($request->input('manage'))
        {
            $manage = $request->input('manage');
        }

        //  订单号
        if(!$request->has('order_id') && empty($request->input('order_id')))
        {
            self::ShowError(ErrorDefine::ORDER_NO_NOT_EXIST);
            return;
        }
        $order_no = $request->input('order_id');


        if($account_type != '测试')
        {

            //   日期卡类型
            if(!$request->has('date_type') && empty($request->input('date_type')))
            {
                self::ShowError(ErrorDefine::DATE_TYPE_NOT_EXIST);
                return;
            }
            $date_type = $request->input('date_type');



            //     开通时间
            if(!$request->has('date') && empty($request->input('date')))
            {
                self::ShowError(ErrorDefine::DATE_NOT_EXIST);
                return;
            }

            $date = $request->input('date');


            if($date<=0) {
                self::ShowError(ErrorDefine::INVALID_DATE);
                return;
            }

            // 价格
            if(!$request->has('price') && empty($request->input('price')))
            {
                self::ShowError(ErrorDefine::PEICE_NOT_EXIST);
                return;
            }
            $price = $request->input('price');

        }



//           用户类型   1   是普通用户  暂时默认普通
        if(!$request->has('set-meal-type') && empty($request->input('set-meal-type')))
        {
            self::ShowError(ErrorDefine::USER_TYPE_NO_EXIST);
            return;
        }
        $set_meal_type = $request->input('set-meal-type');


        //   获取用户ID
        $users = self::getTokenById($token);

        if(empty($users))
        {
            return self::ShowError(ErrorDefine::TOKEN_IS_EXPIRERD);
        }

        $manage_id =  $users[0]['manage_id'];


        //   判断   余额是否支持开户
        if($account_type !='测试')
        {
            if( $users[0]['balance'] < $price)
            {
                return self::ShowError(ErrorDefine::BALANCE_NOT_ENGOUTH);
            }
        }



        //   检测用户名是否存在
        $user = Radcheck::where('username',$username)->get(['id','username'])->toArray();
        if(!empty($user))
        {
            self::ShowError(ErrorDefine::USER_IS_EXIST);
            return;
        }

        // 开户时间  测试一小时
        if($account_type !='测试') {
            switch ($date_type) {
                case '日':
                    $expired_at = time() + 86400 * $date * 1;
                    break;
                case '周':
                    $expired_at = time() + 86400 * $date * 7;
                    break;
                case '月':
                    $expired_at = time() + 86400 * $date * 30;
                    break;
            }
        }else{
            $expired_at = time()+3600;
        }

        //   到期时间
        $time = date("d M Y H:i:s ",$expired_at);


//      添加用户
        $where = [];
        $where['username'] =$username;
        $where['value'] =$password;
        $where['attribute'] ='Cleartext-Password';
        $where['op'] =':=';

        $account_id = Radcheck::insertGetId($where);

        //   添加到期时间
        $arr = [];
        $arr['username'] =$username;
        $arr['attribute'] ='Expiration';
        $arr['op'] =':=';
        $arr['value'] = $time;

        Radcheck::insertGetId($arr);


        //   用户账号表
        $account = [];

        $account['manage_id'] = $manage_id;
        $account['user_id'] = $account_id;
        $account['username'] = $username;
        $account['password'] = $password;
        $account['terrace_id'] = 5;             //  平台标识  5 代理平台
        $account['con_max'] =$concent_num ;
        $account['created_at'] = date('Y-m-d H:i:s',time());
        $account['updated_at'] = date('Y-m-d H:i:s',time());
        $account['expired_at'] = date('Y-m-d H:i:s',$expired_at);
        $account['account_type'] = $account_type;
        $account['vip'] = 1;
        $account['remark'] = $remark;
        $account['set_meal_type'] = $set_meal_type;     //  套餐类型  1：基础  2：初级  3：高级
        if($account_type !='测试')
        {
            $account['balance'] = $price;
        }

        $ret = Rad_users::insertGetId($account);



        //   用户所属组  即连接数
        $group = Radgroupcheck::where('value',$concent_num)->get()->toArray();

//        // 为空  则添加组
        if(empty($group))
        {
            //   添加组
            $group_parm = [];
            $group_parm['groupname'] = 'c'.$concent_num;
            $group_parm['attribute'] = 'Simultaneous-Use';
            $group_parm['op'] = ':=';
            $group_parm['value'] = $concent_num;
            Radgroupcheck::insertGetId($group_parm);
            //   添加组的属性

            //  属性1
            $group_attribute1= [];
            $group_attribute1['groupname'] = 'c'.$concent_num;
            $group_attribute1['attribute'] = 'Auth-Type';
            $group_attribute1['op'] = ':=';
            $group_attribute1['value'] = 'Local';


            //  属性2
            $group_attribute2= [];
            $group_attribute2['groupname'] = 'c'.$concent_num;
            $group_attribute2['attribute'] = 'Service-Type';
            $group_attribute2['op'] = ':=';
            $group_attribute2['value'] = 'Framed-User';


            //  属性3
            $group_attribute3= [];
            $group_attribute3['groupname'] = 'c'.$concent_num;
            $group_attribute3['attribute'] = 'Framed-IP-Address';
            $group_attribute3['op'] = ':=';
            $group_attribute3['value'] = '255.255.255.255';

            $group_attribute4= [];
            $group_attribute4['groupname'] = 'c'.$concent_num;
            $group_attribute4['attribute'] = 'Framed-IP-Netmask';
            $group_attribute4['op'] = ':=';
            $group_attribute4['value'] = '255.255.255.0';

            Radgroupreply::insertGetId($group_attribute1);
            Radgroupreply::insertGetId($group_attribute2);
            Radgroupreply::insertGetId($group_attribute3);
            Radgroupreply::insertGetId($group_attribute4);
        }
//

        //   添加用户与组的对应关系
        $user_group = [];
        $user_group['username'] = $username;
        $user_group['groupname'] = 'c'.$concent_num;
        $user_group['priority'] = 1;
        Radusergroup::insertGetId($user_group);



        $radreply = Radreply::where('username',$username)->get()->toArray();

        if(empty($radreply))
        {
            $param['username'] = $username;
            $param['attribute'] = 'Mikrotik-Rate-Limit';
            $param['op'] = '=';

            switch($set_meal_type)
            {
                case 1: $param['value'] = '512k/512k';break;
                case 2:  $param['value'] = '2048k/2048k';break;
                case 3: $param['value'] = '4096k/4096k';break;
            }
            $id = Radreply::insertGetId($param);
        }


        //   订单信息

        $oder = [];
        if($account_type !='测试')
        {
            $order['balance'] = $users[0]['balance']-$price;
            $order['date'] =$date;
            $order['price'] =$price;
        }else{
            $order['balance'] = $users[0]['balance'];
            $order['date'] = 0;
            $order['price'] =0;
        }

        $order['account_type'] = $account_type;
        $order['connect_num'] =$concent_num;
//        $order['agent_id'] =   $agent;                           //   代理平台标识
//        $order['manage_id'] =   $manage;                       //   代理平台标识


        $order['user_id'] = $manage_id;                 //   用户id

        $order['to_user'] =$account_id;
        $order['order_no'] =$order_no;
        $order['pay_channel'] =2;                    //    支付标识   余额  2


        $order['created_at'] = date('Y-m-d H:i:s',time());
        $order['updated_at'] = date('Y-m-d H:i:s',time());

        $id = Rad_order::insertGetId($order);

        if($id)
        {
            $orders = Rad_order::find($id);
            $orders->status = 1;
            $orders->save();
        }

        if($account_type !='测试')
        {
            $user = Rad_manage::find($manage_id);
            $user->balance = $user->balance - $price;
            $user->save();
        }


        //  添加后台专用数据表
//        $params = [];
//        $params['id'] = $account_id;
//        $params['username'] = $username;
//        $params['password'] = $password;
//        $params['connect_num'] = $concent_num;
//        $params['created_at'] = date('Y-m-d H:i:s',time());
//        $params['expired_at'] = date('Y-m-d H:i:s',$expired_at);
//        $params['account_type'] = $account_type;
//        $params['remark'] = $remark;
//        $params['manage_id'] = $manage_id;
//        $params['terrace_name'] ='manage.niumoip.com';
//        $params['manage_name'] = Rad_manage::find($manage_id)->username;
//
//
//        switch($set_meal_type)
//        {
//            case 1: $params['value'] = '512k/512k';break;
//            case 2:  $params['value'] = '2048k/2048k';break;
//            case 3: $params['value'] = '4096k/4096k';break;
//        }
//
//        Manage_user_list::insertGetId($params);

        return self::ShowMessage();

    }



    /**
     * @param Request $request
     * 续费
     */
    public function renewAccount(Request $request)
    {
        if(empty($request->all()))
        {
            self::ShowError(ErrorDefine::EMPTY_POST_DATA);
            return;
        }

        //  名称
        if(!$request->has('username') && empty($request->input('username')) )
        {
            self::ShowError(ErrorDefine::NAME_NOT_EXIST);
            return;
        }
        $username = $request->input('username');

        //  密码
        if(!$request->has('password') && empty($request->input('password')))
        {
            self::ShowError(ErrorDefine::SHORT_OF_PASSWORD);
            return;
        }
        $password = $request->input('password');


        //  账号类型
        if(!$request->has('renew_type') && empty($request->input('renew_type')))
        {
            self::ShowError(ErrorDefine::DATE_TYPE_NOT_EXIST);
            return;
        }
        $renew_type = $request->input('renew_type');


        //  连接数
        if(!$request->has('connect_num') && empty($request->input('connect_num')) )
        {
            self::ShowError(ErrorDefine::CONCENT_NOT_EXIST);
            return;
        }
        $connect_num = $request->input('connect_num');

        //   检测连接数
        if($connect_num <=0 )
        {
            self::ShowError(ErrorDefine::ILLEGAL_CONNECT_NUM);
            return;
        }


        //   用户token
        if(!$request->has('token') && !empty($request->input('token')))
        {
            self::ShowError(ErrorDefine::TOKEN_NOT_EXIST);
            return;
        }
        $token = $request->input('token');


        if(!$request->has('renew_date') && empty($request->input('renew_date')))
        {
            self::ShowError(ErrorDefine::DATE_NOT_EXIST);
            return;
        }
        $renew_date= $request->input('renew_date');

        if($renew_date<=0) {
            self::ShowError(ErrorDefine::INVALID_DATE);
            return;
        }

        //  订单号
        if(!$request->has('order_id') && empty($request->input('order_id')))
        {
            self::ShowError(ErrorDefine::ORDER_NO_NOT_EXIST);
            return;
        }
        $order_no = $request->input('order_id');


        // 价格
        if(!$request->has('price') && empty($request->input('price')))
        {
            self::ShowError(ErrorDefine::PEICE_NOT_EXIST);
            return;
        }
        $price = $request->input('price');


        if(!$request->has('renew_type') && empty($request->input('renew_type')))
        {
            self::ShowError(ErrorDefine::PEICE_NOT_EXIST);
            return;
        }
        $renew_type = $request->input('renew_type');



        //   获取用户ID
        $user = self::getTokenById($token);
        if(empty($user))
        {
            return self::ShowError(ErrorDefine::TOKEN_IS_EXPIRERD);
        }


        $manage_id =  $user[0]['manage_id'];

        if( $user[0]['balance'] < $price)
        {
            return self::ShowError(ErrorDefine::BALANCE_NOT_ENGOUTH);
        }


        switch ($renew_type) {
            case '日':
                $expired_at = time() + 86400 * $renew_date * 1;
                break;
            case '周':
                $expired_at = time() + 86400 * $renew_date * 7;
                break;
            case '月':
                $expired_at = time() + 86400 * $renew_date * 30;
                break;
        }




//        dd(date("Y-m-d H:i:s ",$expired_at));

        $where = [];
        $where['username'] = $username;
        $where['attribute'] = 'Expiration';
        $where['op'] = ':=';


        $rad = Radcheck::where($where)->get();


        if(strtotime($rad[0]->value) > time())
        {
            $expired_at = strtotime($rad[0]->value) + $expired_at - time();
        }

        $time = date("d M Y H:i:s ",$expired_at);

        $rad[0]->value=$time;
        $rad[0]->save();


        $where2 = [];

        $where2['username'] = $username;
        $ret = Rad_users::where($where2)->get();

        $ret[0]->updated_at = date('Y-m-d H:i:s',time());
        $ret[0]->expired_at = date('Y-m-d H:i:s',$expired_at);
        $ret[0]->balance = $ret[0]->balance + $price;
        $ret[0]->account_type = '付费';
        $ret[0]->save();

        $oder = [];

        $order['balance'] = $user[0]['balance']-$price;
        $order['date'] =$renew_date;
        $order['price'] =$price;

        $order['account_type'] = '付费';
        $order['connect_num'] =$connect_num;
        $order['user_id'] = $manage_id;
        $order['order_no'] =$order_no;
        $order['created_at'] = date('Y-m-d H:i:s',time());
        $order['updated_at'] = date('Y-m-d H:i:s',time());

        Rad_order::insertGetId($order);

        $user = Rad_manage::find($manage_id);

        $user->balance = $user->balance - $price;
        $user->save();


        return self::ShowMessage();

    }
    

    

    /**
     * @param Request $request
     * 更新账户信息
     */
	public function updateAcouunt(Request $request)
	{
		if(empty($request->all()))
		{
			self::ShowError(ErrorDefine::EMPTY_POST_DATA);
			return;
		}

		$where=  [];
		//  用户名
		if(!$request->has('username') && !empty($request->input('username')) )
		{
			self::ShowError(ErrorDefine::NAME_NOT_EXIST);
			return;
		}
		$where['username'] = trim($request->input('username'));





		// 密码
		if(!$request->has('password') && !empty($request->input('password')))
		{
			self::ShowError(ErrorDefine::SHORT_OF_PASSWORD);
			return;
		}

		$where['value'] = trim($request->input('password'));





		//  账号ID
		if(!$request->has('account_id') && !empty($request->input('account_id')))
		{
			self::ShowError(ErrorDefine::ACCOUNT_ID_NOT_EXIST);

		}
		$user_id = $request->input('account_id');



		$remark = '';
		if($request->has('remark'))
		{
			$remark = $request->input('remark');
		}
		$speed = '';

		//  限速的速度
		if($request->has('speed') && !empty($request->input('speed')))
		{
			$speed = $request->input('speed');
		}



		if($request->has('set-meal-type'))
		{
			$set_meal_type = $request->input('set-meal-type');
		}else{
			$users  = Rad_users::find($user_id);
			$set_meal_type = $users->set_meal_type;
		}


		// 获取用户信息
		$user = Rad_users::find($user_id)->toArray();

		//   检测新的用户名是否被使用
		$info = Radcheck::where('username',$where['username'])->get()->toArray();

		if(!empty($info))
		{
			if($user['username'] != $info[0]['username'])
			{
				self::ShowError(ErrorDefine::ACCOUNT_IS_EXIST);
				return;
			}
		}

		if($speed)
		{
			//  限速修改
			$radreply = Radreply::where('username',$user['username'])->where('attribute','Mikrotik-Rate-Limit')->first();
			$radreply->username = $where['username'];
			$radreply->value = $speed;
			$radreply->save();
		}



		//  更新用户表内用户信息
		$ret1 = Radcheck::where('username',$user['username'])->where('id',$user_id)->update($where);

		$ret2 = Radcheck::where('username',$user['username'])->where('attribute','=','Expiration')->update(['username'=>$where['username']]);

		// 更新用户组信息
		$ret3 = Radusergroup::where('username',$user['username'])->update(['username'=>$where['username']]);

		Rad_users::where('username',$user['username'])->where('user_id','=',$user_id)->update(['username'=>$where['username'],'password'=>$where['value'],'remark'=>$remark,'set_meal_type'=>$set_meal_type]);

		return self::ShowMessage();


	}





    /**
     * @param Request $request
     * 某一账户在线信息
     */
    public function getAccountOnlineInfo(Request $request)
    {
        $account_id  = $request->input('account_id');

        $user = Radcheck::find($account_id);

        $online = [];
        $result = DB::connection('mysql_concent')->select("SELECT * FROM radacct WHERE (acctstoptime IS  NULL AND UNIX_TIMESTAMP(acctstarttime) + acctsessiontime +100  > UNIX_TIMESTAMP() ) and  username = '{$user->username}'");
        foreach($result as $key=>$value)
        {
            $online[$key]['radacctid'] = $value->radacctid;
            $online[$key]['acctsessionid'] = $value->acctsessionid;
            $online[$key]['username'] = $value->username;
            $online[$key]['calledstationid'] = $value->calledstationid;
            $online[$key]['framedipaddress'] = $value->framedipaddress;
            $online[$key]['acctstarttime'] = $value->acctstarttime;
        }

        $data=array(
            'online'=>$online
        );
        return self::ShowMessage($data);

    }




    /**
     * @param Request $request
     * 禁用用户
     */
    public function forbiddenAccount(Request $request)
    {

        $data =  $where = $request->all();;
        $data = http_build_query($data);

        $out = "GET http://121.196.202.198 HTTP/1.1\r\n";  // 通过POST方式发送数据
        $out .= "121.196.202.198\r\n";
        $out .= "Content-type: application/x-www-form-urlencoded; charset=UTF-8\r\n";
        $out .= "Content-length: ".strlen($data)."\r\n";
        $out .= "User-Agent: Mozilla/5.0 (Windows NT 6.1; rv:48.0) Gecko/20100101 Firefox/48.0"."\r\n";
        $out .= "Connection: close"."\r\n"."\r\n";    // 注意：此处有两个 \r\n

        $out .= $data."\r\n";   // 正文数据

        $fp = fsockopen("121.196.202.198", 17332, $errno, $errstr, 30);  // 创建socket客户端连接


        fwrite($fp, $out);    // 向服务器发送数据

//        while (!feof($fp)) {
            $status =  fgets($fp, 1280);    // 读取服务器响应的数据
//        }


        return self::ShowMessage($status);

    }



    // 账号线路在线列表
    public function getOnlineList(Request $request)
    {

        $end_date = date('Y-m-d H:i:s');
        $start_date = '1970-01-01 08:00:00';

        if(!$request->has('token') && empty($request->input('token')))
        {
            self::ShowError(ErrorDefine::TOKEN_NOT_EXIST);
            return;
        }
        $token = $request->input('token');

        //   获取用户ID

        if($request->has('end_date') && !empty($request->input('end_date')))
        {
            $end_date = $request->input('end_date');
        }

        if($request->has('start_date') && !empty($request->input('start_date')))
        {
            $start_date = $request->input('start_date');
        }


        $user = self::getTokenById($token);

        if(empty($user))
        {
            self::ShowError(ErrorDefine::TOKEN_IS_EXPIRERD);
            return;
        }


        $user_id = $user[0]['manage_id'];


        $level = $user[0]['level'];


        $sql=" UNIX_TIMESTAMP(radacct.acctstarttime) + radacct.acctsessiontime +100  > UNIX_TIMESTAMP()";

        $time = date('Y-m-d H:i:s',time());


        switch($level)
        {
            case 1:
                $name = Rad_users::where('manage_id',$user_id)->get(['username']);
                break;

            case 3:
                $name = Rad_users::where('manage_id',$user_id)->get(['username']);
                break;
            case 2:
                $name = Rad_users::where('expired_at','>',$time)->get(['username']);break;

        }

        $field = ['radacct.radacctid','radacct.acctsessionid','radacct.acctstarttime','radacct.username','users.user_id'];

       $radacct = new Radacct();

        $result  = $radacct::select($field)->leftJoin("users", function ($join) {$join->on("radacct.username", "=", "users.username");})
            ->whereIn('radacct.username',$name)->where('radacct.acctstarttime','>',$start_date)
            ->where('radacct.acctstarttime','<',$end_date)->whereNull('radacct.acctstoptime')->whereRaw($sql)
            ->groupBy('radacct.username')->get()->toArray();

        foreach($result as &$value)
        {
            $num = Radacct::where('username',$value['username'])->where('acctstarttime','>',$start_date)
                ->where('acctstarttime','<',$end_date)->whereNull('acctstoptime')->whereRaw($sql)
                ->count();
            $value['num'] = $num;
        }

        $count= 0;
        $count = Radacct::whereIn('username',$name)->where('acctstarttime','>',$start_date)->where('acctstarttime','<',$end_date)->whereNull('acctstoptime')->whereRaw($sql)->count();

        $data=array(
            'num'=>$count,
            'online'=>$result
        );
        return self::ShowMessage($data);

    }


    /**
     * @param Request $request
     * 限速
     */
    public function limitSpeed(Request $request)
    {
        if(!$request->has('token') && empty($request->input('token')))
        {
            self::ShowError(ErrorDefine::TOKEN_NOT_EXIST);
            return;
        }
        $token = $request->input('token');

        $user = self::getTokenById($token);

        if(empty($user))
        {
            self::ShowError(ErrorDefine::TOKEN_IS_EXPIRERD);
            return;
        }

        $user_id = $user[0]['manage_id'];



        if(!$request->has('on-line') || empty($request->input('on-line')))
        {
            self::ShowError(ErrorDefine::UP_LINE_NOT_EXIST);
            return;
        }
        $on_line = $request->input('on-line');

        if(!$request->has('next-line') || empty($request->input('next-line')))
        {
            self::ShowError(ErrorDefine::NEXT_LINE_NOT_EXIST);
            return;
        }

        $next_line = $request->input('next-line');

        if(!$request->has('account_id') || empty($request->input('account_id')))
        {
            self::ShowError(ErrorDefine::ACCOUNT_ID_NOT_EXIST);
            return;
        }

        $account_id = $request->input('account_id');


//        nm99(username)	Mikrotik-Rate-Limit(attribute)	=(op)	64k/64k(value)

        $users = Rad_users::find($account_id);

        $param = [];

        $ret = Radreply::where('username',$users->username)->where('attribute','Mikrotik-Rate-Limit')->first();

        if(empty($ret))
        {
            $param['username'] = $users->username;
            $param['attribute'] = 'Mikrotik-Rate-Limit';
            $param['op'] = '=';
            $param['value'] = $on_line.'k/'.$next_line.'k';

            Radreply::insertGetId($param);


        }else{
            $ret->value =$on_line.'k/'.$next_line.'k';
            $ret->save();
        }

        return self::ShowMessage();

    }


    
    /**
 * @param Request $request
 * 获取用户订单列表
     *
 */
    public function getBillList(Request $request)
    {
        $end_date = date('Y-m-d H:i:s');
        $start_date = '1970-01-01 08:00:00';
        if(!$request->has('token') && empty($request->input('token')))
        {
            self::ShowError(ErrorDefine::TOKEN_NOT_EXIST);
            return;
        }
        $token = $request->input('token');

        //   获取用户ID
        $user = self::getTokenById($token);

        if($request->has('end_date') && !empty($request->input('end_date')))
        {
            $end_date = $request->input('end_date');
        }

        if($request->has('start_date') && !empty($request->input('start_date')))
        {
            $start_date = $request->input('start_date');
        }


        if(empty($user))
        {
            return self::ShowError(ErrorDefine::TOKEN_IS_EXPIRERD);
        }
        $user_id =  $user[0]['manage_id'];
        $data = [];

        $orders = Rad_order::where('user_id',$user_id)->where('created_at','>',$start_date)->where('created_at','<',$end_date)->orderBy('created_at','desc')->orderBy('balance','asc')->get(['order_no','date','account_type','balance','price','created_at'])->toArray();
        $data['orders'] = $orders;
        return self::ShowMessage($data);



    }


    /**
     *用户线路删除
     */
    public function deleteAccountLine(Request $request)
    {
        if(!$request->has('token') && empty($request->input('token')))
        {
            self::ShowError(ErrorDefine::TOKEN_NOT_EXIST);
            return;
        }
        $token = $request->input('token');


        $user = self::getTokenById($token);

        $manage_id = $user[0]['manage_id'];
        $level= $user[0]['level'];

        $id  = $request->input('id');

        $id = explode(',',$id);

        foreach($id as $value)
        {
            $this->module->DeleteAccount($manage_id,$level,$value);
        }

        return self::ShowMessage('SUCCESS');


    }
    
    

    
    
    /**
     * @param $token
     * @return mixed
     * token   换取 用ID
     */
    static function getTokenById($token)
    {
        $user = Rad_manage::where('token',$token)->get()->toArray();
        return $user;
    }




}


